import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {NonNullableFormBuilder, Validators} from '@angular/forms';
import {Subject} from 'rxjs';
import {AuthService} from '../../services/auth.service';
import {Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd/message';

@Component({
  selector: 'app-register',
  standalone: false,
  templateUrl: './register.component.html',
  styleUrl: './register.component.css'
})
export class RegisterComponent implements OnInit, OnDestroy {
  private fb = inject(NonNullableFormBuilder);
  private authService = inject(AuthService);
  private destroy$ = new Subject<void>();
  private router = inject(Router);
  private message = inject(NzMessageService);
  validateForm = this.fb.group({
    nickname: this.fb.control('', [Validators.required, Validators.minLength(3)]),
    email: this.fb.control('', [Validators.email, Validators.required]),
    password: this.fb.control('', [Validators.required]),
    checkPassword: this.fb.control('', [Validators.required]),
    agree: this.fb.control(false)
  });

  ngOnInit(): void {

  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  submitForm(): void {
    const password = this.validateForm.controls.password.value;
    const checkPassword = this.validateForm.controls.checkPassword.value;

    if (password !== checkPassword) {
      this.validateForm.controls.checkPassword.setErrors({ confirm: true, error: true });
      this.validateForm.controls.checkPassword.markAsDirty();
      return;
    }
    if(!this.validateForm.controls.agree.value){
      this.message.error('未阅读用户协议');
      return;
    }

    if (this.validateForm.valid) {
      const registerData = {
        username: this.validateForm.controls.nickname.value,
        email: this.validateForm.controls.email.value,
        password: this.validateForm.controls.password.value,
      }

      this.authService.register(registerData).subscribe({
        next: () => {
          this.message.success('注册成功！！！')
          this.router.navigate(['/login']);
        }
      })
      // console.log('submit', this.validateForm.value);
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
}
